package main

import (
    "net/http"
    "io/ioutil"
    "strings"
    "launchpad.net/mgo"
)

type ebook struct {
    Name string
    Author []string
}

func main() {
    books := search("math")

    session, err := mgo.Dial("localhost")
    if err != nil {
        panic(err)
    }
    defer session.Close()

    session.SetMode(mgo.Monotonic, true)

    c := session.DB("book").C("bookfi")
    for _, v := range books {
        err = c.Insert(v)
        if err != nil {
            panic(err)
        }
    }
    if err != nil {
        panic(err)
    }
}

func search(keyword string) []ebook {
    resq, _ := http.Get("http://en.bookfi.org/s/?q=" + keyword)
    body, _ := ioutil.ReadAll(resq.Body)
    page := string(body)

    res := make([]ebook, 100)
    for k := 0; k < 100; k++ {
        n := strings.Index(page, "itemprop=\"name")
        if n == -1 {
            break
        }
        page = page[n+16:]
        nameEnd := strings.Index(page, "<")
        res[k].Name = page[:nameEnd]
        iStart := strings.Index(page, "<i>")
        iEnd := strings.Index(page, "</i>")
        sI := page[iStart:iEnd]
        for {
            authorStart := strings.Index(sI, "href=\"g/")
            authorEnd := strings.Index(sI, "\">")
            if authorStart == -1 || authorEnd == -1 {
                break
            }
            res[k].Author = append(res[k].Author, sI[authorStart+8:authorEnd])
            sI = sI[authorEnd+2:]
        }
    }
   return res
}
